package com.ruoyi.web.controller.module.event;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.QRCodeUtilEx;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.module.event.*;
import com.ruoyi.system.domain.module.property.Property;
import com.ruoyi.system.domain.module.survey.Survey;
import com.ruoyi.system.service.module.estate.IEstateService;
import com.ruoyi.system.service.module.event.*;
import com.ruoyi.system.service.module.property.IPropertyService;
import com.ruoyi.system.service.module.survey.ISurveyService;
import com.ruoyi.web.controller.common.BaseController;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 巡更点Controller
 *
 * @author ruoyi
 * @date 2023-12-26
 */
@Validated
@Api(value = "巡更点控制器", tags = {"巡更点管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/event/patrol/point")
public class EventPatrolPointController extends BaseController {

    private final IEventPatrolPointService eventPatrolPointService;
	private final IPropertyService propertyService;
	private final IEstateService estateService;
	private final ISurveyService surveyService;
	private final IEventPointQrInfoService eventPointQrInfoService;
	private final IEventPlanTaskInfoService eventPlanTaskInfoService;
	private final IEventPatrolLineInfoService eventPatrolLineInfoService;
	@Value("${ruoyi.profile}")
	private String uploadPath;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;
    /**
     * 查询巡更点列表
     */
    @ApiOperation("查询巡更点列表")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:list')")
    @GetMapping("/list")
    public TableDataInfo<EventPatrolPoint> list(@Validated EventPatrolPoint eventPatrolPoint) {
		SysUser sysUser = getUser();

		QueryWrapper<EventPatrolPoint> qw = new QueryWrapper<>();
		//用户类型 0 - 系统管理员  1 - 平台管理员 2 - 物业管理员  3 - 小区管理员
		if(sysUser.getUserType() == 2){
			qw.eq("property_id",sysUser.getPropertyId());
			if (sysUser.getEstateId()!=null){
				qw.eq("estate_id",sysUser.getEstateId());
			}
		} else if(sysUser.getUserType() == 3){
			qw.eq("estate_id",sysUser.getEstateId());
		}else{
			if(eventPatrolPoint.getPropertyId() != null){
				qw.eq("property_id",eventPatrolPoint.getPropertyId());
			}
			if(eventPatrolPoint.getEstateId() != null){
				qw.eq("estate_id",eventPatrolPoint.getEstateId());
			}
		}

        TableDataInfo<EventPatrolPoint> td = PageUtils.buildDataInfo(eventPatrolPointService.page(PageUtils.buildPage(),qw));
        List<EventPatrolPoint> list = td.getRows();
		for (EventPatrolPoint list1:list){

			if(StrUtil.isNotEmpty(list1.getQrCode())){
				list1.setQrCode(imgUrl + list1.getQrCode());
			}
			if (list1.getPropertyId()!=null){
				list1.setPropertyName(propertyService.findById(list1.getPropertyId()).getPropertyName());
			}
			if (list1.getEstateId()!=null){
				list1.setEstateName(estateService.findById(list1.getEstateId()).getEstateName());
			}
			if (list1.getSurveyStandardId()!=null){
				Survey survey = surveyService.getById(list1.getSurveyStandardId());
				if (survey!=null){
					list1.setSurveyStandardinfo(survey.getSurveyInfo());
					list1.setSurveyStandardName(survey.getQuestionTitle());
				}
			}
			if (list1.getSurveyTemplateId()!=null){
				Survey survey = surveyService.getById(list1.getSurveyTemplateId());
				if (survey!=null){
					list1.setSurveyTemplateinfo(survey.getSurveyInfo());
					list1.setSurveyTemplateName(survey.getQuestionTitle());
				}
			}
		}
        return td;
    }

    /**
     * 导出巡更点列表
     */
    @ApiOperation("导出巡更点列表")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:export')")
    @Log(title = "巡更点", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<EventPatrolPoint> export(@Validated EventPatrolPoint eventPatrolPoint) {
        List<EventPatrolPoint> list = eventPatrolPointService.list();
        ExcelUtil<EventPatrolPoint> util = new ExcelUtil<EventPatrolPoint>(EventPatrolPoint.class);
        return util.exportExcel(list, "巡更点");
    }

    /**
     * 获取巡更点详细信息
     */
    @ApiOperation("获取巡更点详细信息")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:query')")
    @GetMapping("/{id}")
    public AjaxResult<EventPatrolPoint> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Integer id) {
        EventPatrolPoint point = eventPatrolPointService.getById(id);
		if(point != null){
			if(StrUtil.isNotEmpty(point.getQrCode())){
				point.setQrCode(imgUrl + point.getQrCode());
			}
		}
        return AjaxResult.success(point);
    }

	/**
	 * 修改巡检设备状态
	 */
	@ApiOperation("修改巡更点")
	@PreAuthorize("@ss.hasPermi('module:patrolPoint:edit')")
	@Log(title = "巡更点", businessType = BusinessType.UPDATE)
	@RepeatSubmit
	@PutMapping("/updateState")
	public AjaxResult<Void> editState(@Validated(EditGroup.class) @RequestBody EventPatrolPoint eventPatrolPoint) {
		EventPatrolPoint points = eventPatrolPointService.getById(eventPatrolPoint.getId());
		points.setState(eventPatrolPoint.getState());
		//查询所有巡更设备info
		if (eventPatrolPoint.getState()==0){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",1);
			qw.eq("state",0);
			qw.eq("target_id",eventPatrolPoint.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(3L);
				eventPlanTaskInfoService.updateById(info);
			}
			//产出巡更点中的路线
//			QueryWrapper<EventPatrolLineInfo> qw1 = new QueryWrapper<>();
//			qw1.eq("point_id",eventPatrolPoint.getId());
//			List<EventPatrolLineInfo> infoList = eventPatrolLineInfoService.list(qw1);
//			if (infoList.size()>0){
//				for (EventPatrolLineInfo info : infoList){
//					eventPatrolLineInfoService.removeById(info.getId());
//				}
//			}
		}
		if (eventPatrolPoint.getState()==1){
			QueryWrapper<EventPlanTaskInfo> qw = new QueryWrapper<>();
			qw.eq("target_type",1);
			qw.eq("state",3);
			qw.eq("target_id",eventPatrolPoint.getId());
			List<EventPlanTaskInfo> infos = eventPlanTaskInfoService.list(qw);
			for (EventPlanTaskInfo info:infos){
				info.setState(0L);
				eventPlanTaskInfoService.updateById(info);
			}
		}
		return toAjax(eventPatrolPointService.updateById(points) ? 1 : 0);
	}

    /**
     * 新增巡更点
     */
    @ApiOperation("新增巡更点")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:add')")
    @Log(title = "巡更点", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody EventPatrolPoint eventPatrolPoint) {
		boolean bl = eventPatrolPointService.save(eventPatrolPoint);
		try{
			String fileName = "patrol_qr_" + eventPatrolPoint.getId() + ".jpg";
			String content = "https://www.caihengyun.com/wxmini/patrol/info?id=" + eventPatrolPoint.getId();
			int upload_type = FileUploadUtils.TYPE_TERMINALS;
			System.out.println("content:  "+ content);
			String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, eventPatrolPoint.getPatrolTitle(), null,
				uploadPath +"/"+img_key, true, fileName, upload_type);
			eventPatrolPoint.setQrCode(img_key);
			if (eventPatrolPoint.getPointQrInfoId()!=null){
				EventPointQrInfo info = eventPointQrInfoService.findById(eventPatrolPoint.getPointQrInfoId());
				if (info!=null){
					eventPatrolPoint.setPointQrId(info.getPointQrId());
				}
			}
			eventPatrolPointService.updateById(eventPatrolPoint);
		}catch (Exception ex){
			ex.printStackTrace();
		}

        return toAjax(bl ? 1 : 0);
    }


	/**
	 * 重置二维码
	 */
	@Log(title = "重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@ss.hasPermi('module:patrolPoint:edit')")
	public AjaxResult<Void> resetQrCode(@RequestBody EventPatrolPoint eventPatrolPoint) {
		if(eventPatrolPoint.getId()!=null){
			try{
				eventPatrolPoint = eventPatrolPointService.getById(eventPatrolPoint.getId());
				String fileName = "patrol_qr_" + eventPatrolPoint.getId() + ".jpg";
				String content = "https://www.caihengyun.com/wxmini/patrol/info?id=" + eventPatrolPoint.getId();
				int upload_type = FileUploadUtils.TYPE_TERMINALS;
				System.out.println("content:  "+ content);
				String img_key = FileUploadUtils.getUploadPrefix(upload_type) + fileName;
				QRCodeUtilEx.createQrCodeImg(content, eventPatrolPoint.getPatrolTitle(), null, uploadPath +"/"+img_key, true, fileName, upload_type);
				eventPatrolPoint.setQrCode(img_key);
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (eventPatrolPointService.updateById(eventPatrolPoint)) {
				return AjaxResult.success();
			}
		}
		return AjaxResult.error();
	}


	/**
     * 修改巡更点
     */
    @ApiOperation("修改巡更点")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:edit')")
    @Log(title = "巡更点", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody EventPatrolPoint eventPatrolPoint) {
		if (eventPatrolPoint.getPointQrInfoId()!=null){
			EventPointQrInfo info = eventPointQrInfoService.findById(eventPatrolPoint.getPointQrInfoId());
			if (info!=null){
				eventPatrolPoint.setPointQrId(info.getPointQrId());
			}
		}
        return toAjax(eventPatrolPointService.updateById(eventPatrolPoint) ? 1 : 0);
    }

    /**
     * 删除巡更点
     */
    @ApiOperation("删除巡更点")
    @PreAuthorize("@ss.hasPermi('module:patrolPoint:remove')")
    @Log(title = "巡更点" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(eventPatrolPointService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
